package myJs.cps

import myJs.Implicits._
import myJs.api.Api
import myJs.myPkg.RSelect.{AsyncPaginate, LoadOptionsR, Select, SelectOption}
import myJs.myPkg.jquery.{$, JQuery}
import myJs.myPkg.reactHookForm.{Controller, FieldR, RegisterOptions, UseFormRT}
import myJs.myPkg._
import org.scalajs.dom.{Event, html}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.{Fragment, React, ReactElement}
import slinky.web.html._

import scala.collection.immutable.SeqMap
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSON
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Sample.GetAllNoUsedId

/**
 * Created by yz on 21/1/2022
 */
@react object PureAsyncRSelectCp {

  case class Props(
                    name: String = "",
                    value: String,
                    onChange: String => Unit,
                    registerOptions: RegisterOptions,
                    useForm: UseFormRT,
                  )

  val component = FunctionalComponent[Props] { props =>

    object FTool {

    }

    val valueOp = props.useForm.watch(props.name)

    useEffect(() => {
      val v = valueOp.toSelectionOption.map { value =>
        value.value
      }.getOrElse {
        ""
      }
      props.onChange(v)
    }, List(valueOp)
    )

    Fragment(
      Controller(
        name = props.name,
        control = props.useForm.control,
        rules = props.registerOptions,
        render = (fieldR: FieldR) => {
          val field = fieldR.field
          val fieldValue = field.value.toSelectionOption
          AsyncPaginate(onChange = field.onChange, placeholder = "点击选择", name = field.name,
            value = fieldValue, ref = field.ref,
            loadOptions = (search: String, prevOptions: List[SelectOption]) => {
              val request = GetAllNoUsedId.Request(q = search, hasShowNum = prevOptions.size, pageSize = 10)
              Api.sample.getAllNoUsedId(request).map { response =>
                val options = response.results.map { x =>
                  SelectOption(label = x.text, value = x.id)
                }
                LoadOptionsR(options = options, hasMore = response.pagination.more)
              }

            }
          ): ReactElement
        }
      ),
      if (props.useForm.formState.errors.isDefinedAt(props.name)) {
        small(className := "help-block", props.useForm.formState.errors(props.name).message)
      } else null
    )

  }

}
